﻿using System;
using System.Collections.Generic;
using System.Net;

namespace DSAServer.Utils
{
    public class UrlHelper
    {
        /// <summary>
        /// 获取一个网址的参数列表
        /// </summary>
        /// <param name="url">网址</param>
        /// <returns>参数列表</returns>
        public static List<KeyValuePair<string, string>> GetParas(string url)
        {
            List<KeyValuePair<string, string>> paras = new List<KeyValuePair<string, string>>();
            Uri uri = new Uri(url);
            if (url.Contains("?"))
            {
                int pos = url.IndexOf('?') + 1;
                string queryStr = url.Substring(pos, url.Length - pos);// url.Split('?')[1];
                string[] kvs = queryStr.Split('&');
                foreach (string kv in kvs)
                {
                    if (string.IsNullOrEmpty(kv.Trim())) continue;
                    //找出第1个=的位置
                    int pos1 = kv.IndexOf("=");
                    if (pos1 > -1)
                    {
                        string key = kv.Substring(0, pos1);
                        string value = kv.Substring(pos1 + 1, kv.Length - pos1 - 1);
                        paras.Add(new KeyValuePair<string, string>(key, value));
                    }
                    else
                    {
                        paras.Add(new KeyValuePair<string, string>(kv, ""));
                    }

                    //string[] kvstr = kv.Split('=');
                    //if (kvstr.Length == 2)
                    //    paras.Add(new KeyValuePair<string, string>(kvstr[0], kvstr[1]));
                    //else
                    //{
                    //    paras.Add(new KeyValuePair<string, string>(kvstr[0], ""));
                    //}
                }
            }
            return paras;
        }

        public static string GetParaValue(string url, string key)
        {
            List<KeyValuePair<string, string>> paras = GetParas(url);
            foreach (KeyValuePair<string, string> keyValuePair in paras)
            {
                if (keyValuePair.Key.ToLower() == key.ToLower())
                    return keyValuePair.Value;
            }
            return "";
        }

        /// <summary>
        /// 去除网址的参数部份
        /// </summary>
        /// <param name="url">返回去除网址参数的url</param>
        /// <returns>网址</returns>
        public static string RemoveQuery(string url)
        {
            if (url.Contains("?"))
            {
                return url.Split('?')[0];
            }
            else
            {
                return url;
            }
        }

        /// <summary>
        /// 移除网址中指定的参数
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="paraNames">需要去除的参数列表</param>
        /// <returns>网址</returns>
        public static string RemovePara(string url, params string[] paraNames)
        {
            string address = RemoveQuery(url);
            List<KeyValuePair<string, string>> paras = GetParas(url);
            if (paras.Count > 0)
            {
                address += "?";
                int idx = 0;
                foreach (KeyValuePair<string, string> pair in paras)
                {
                    if (Array.IndexOf(paraNames, pair.Key) > -1) continue;
                    if (idx++ > 0) address += "&";
                    address = address + string.Format("{0}={1}", pair.Key, pair.Value);
                }
            }
            return address;
        }

        /// <summary>
        /// 获取一个网址请求后的重定向的列表(主要用于短网址原码)
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="timeOut">请求超时间(单位:ms)</param>
        /// <returns></returns>
        public static List<string> GetRedirectList(string url, int timeOut)
        {
            List<string> redirectUrls = new List<string>();
            redirectUrls.Add(url);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = timeOut;
            request.AllowAutoRedirect = false;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            response.Close();
            int cnt = 0;
            while (response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)
            {
                if (cnt++ > 5) break;

                string location = response.Headers[HttpResponseHeader.Location];
                Uri uri;
                if (!Uri.TryCreate(location, UriKind.Absolute, out uri)) break;
                redirectUrls.Add(location);
                request = (HttpWebRequest)WebRequest.Create(location);
                request.Timeout = timeOut;
                request.AllowAutoRedirect = false;
                response = (HttpWebResponse)request.GetResponse();
                response.Close();
            }
            return redirectUrls;
        }

        /// <summary>
        /// 替换url中某个参数的值
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="para">参数</param>
        /// <param name="value">参数的值</param>
        /// <returns></returns>
        public static string ReplaceParaValue(string url, string para, string value)
        {
            string address = RemoveQuery(url);
            List<KeyValuePair<string, string>> paras = GetParas(url);
            if (paras.Count > 0)
            {
                address += "?";
                int idx = 0;
                bool hasExists = false;
                ;
                foreach (KeyValuePair<string, string> pair in paras)
                {
                    if (idx++ > 0) address += "&";
                    if (pair.Key.ToLower() == para.ToLower())
                    {
                        address = address + string.Format("{0}={1}", pair.Key, value);
                        hasExists = true;
                    }
                    else
                        address = address + string.Format("{0}={1}", pair.Key, pair.Value);
                }
                if (!hasExists)
                {
                    if (idx > 0) address += "&";
                    address = address + string.Format("{0}={1}", para, value);
                }
            }
            else
            {
                address = address + string.Format("?{0}={1}", para, value);
            }

            return address;
        }

    }
}
